import { CustomRequestOptions } from '@/interceptors/request'

export const http = <T>(options: CustomRequestOptions) => {
    // 1. 返回 Promise 对象
    return new Promise<IResData<T>>((resolve, reject) => {
        uni.request({
            ...options,
            dataType: 'json',
            // #ifndef MP-WEIXIN
            responseType: 'json',
            // #endif
            // 响应成功
            success(res: any) {
                if (res.data.code === 401) {
                    uni.showToast({ title: res.data.message, icon: 'none' })
                    setTimeout(() => {
                        uni.navigateTo({ url: '/pages/common/login' })
                    }, 1200);
                } else {
                    resolve(res.data as IResData<T>)
                }
            },
            // 响应失败
            fail(err) {
                uni.showToast({ icon: 'none', title: '无法连接服务器' })
                reject(err)
            },
        })
    })
}

/**
 * GET 请求
 * @param url 后台地址
 * @param query 请求query参数
 * @param header 请求头，默认为json格式
 * @returns
 */
export const httpGet = <T>(
    url: string,
    query?: Record<string, any>,
    header?: Record<string, any>,
) => {
    return http<T>({
        url,
        query,
        method: 'GET',
        header,
    })
}

/**
 * POST 请求
 * @param url 后台地址
 * @param data 请求body参数
 * @param query 请求query参数，post请求也支持query，很多微信接口都需要
 * @param header 请求头，默认为json格式
 * @returns
 */
export const httpPost = <T>(
    url: string,
    data?: Record<string, any>,
    query?: Record<string, any>,
    header?: Record<string, any>,
) => {
    return http<T>({
        url,
        query,
        data,
        method: 'POST',
        header,
    })
}


/**
 * PUt 请求
 * @param url 后台地址
 * @param data 请求body参数
 * @param query 请求query参数
 * @param header 请求头，默认为json格式
 * @returns
 */
export const httpPut = <T>(
    url: string,
    data?: Record<string, any>,
    query?: Record<string, any>,
    header?: Record<string, any>,
) => {
    return http<T>({
        url,
        query,
        data,
        method: 'PUT',
        header,
    })
}

/**
 * DELETE 请求
 * @param url 后台地址
 * @param data 请求body参数
 * @param query 请求query参数 
 * @param header 请求头，默认为json格式
 * @returns
 */
export const httpDelete = <T>(
    url: string,
    data?: Record<string, any>,
    query?: Record<string, any>,
    header?: Record<string, any>,
) => {
    return http<T>({
        url,
        query,
        data,
        method: 'DELETE',
        header,
    })
}


http.get = httpGet
http.post = httpPost
http.put = httpPut
http.delete = httpDelete
